package top.jlzhou.config;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.support.RequestContext;

import top.jlzhou.CodeException;
import top.jlzhou.R;



/**
 * 
 * @ClassName	ExceptionAspect
 * @Description	TODO(将所有控制器的异常转换为CodeExcpetion)
 * @author	J.L.Zhou
 * @date	2019年2月21日 下午1:28:30
 * @version 	V1.0
 * @Copyright	2019 PEPay Inc. All rights reserved. 
 * 	注意：本内容仅限于公司内部传阅，禁止外泄以及用于其他的商业目
 */
public class ExceptionAspect {

	public Object doAround(ProceedingJoinPoint jp)throws Throwable{
		Object ret = null;
		try{
			ret = jp.proceed();
			if(ret instanceof R){
				R r = (R)ret;
				if(r.get("message")!=null && r.get("message") instanceof String){
					 HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
					 RequestContext rc = new RequestContext(request);
					 String message = (String)r.get("message");
					 r.put("message", rc.getMessage(message, message));
				}
			}
		}catch(Throwable ex){
			if(ex instanceof CodeException){
				throw ex;
			}else{
				CodeException e = new CodeException(-1,ex);
				e.setMessage(ex.getMessage());
				throw e;
			}
		}
		return ret;
	}
}
